package xingkong.intecepter;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;

import xingkong.tools.ResponseContent;
import xingkong.tools.StaticFields;

public class MyIntecepter implements Interceptor{
	private Map<String,String> map = new HashMap<String,String>();
	
	public MyIntecepter(){
		this.map.put("/xingkong/user/tologin", "/xingkong/user/tologin");
		this.map.put("/xingkong/user/index", "/xingkong/user/index");
		this.map.put("/xingkong/user/login", "/xingkong/user/login");
		this.map.put("/xingkong/user/toreg", "/xingkong/user/toreg");
		this.map.put("/xingkong/user/toforget", "/xingkong/user/toforget");
		this.map.put("/xingkong/order/countTotal", "/xingkong/order/countTotal");
		this.map.put("/xingkong/user/reg", "/xingkong/user/reg");
		this.map.put("/xingkong/user/admin", "/xingkong/user/admin");
	}
	
	@Override
	public void intercept(Invocation arg0) {
		// TODO Auto-generated method stub
		Controller c = arg0.getController();
//		String key = c.getControllerKey();
		String url = c.getRequest().getRequestURI();
//		System.out.println(key);
		System.out.println(url);
		Record record = (Record) c.getSession().getAttribute(StaticFields.CURRENTUSER);
		if(null != record){
//			if(StringUtils.isEmpty(map.get(url))){
				arg0.invoke();
//			}else {
//				if(isAjax(c)){
//					c.renderJson(new ResponseContent(StaticFields.WRONG, "请求不正常", null));
//					return;
//				}
//				c.redirect("/user/index");
//			}
		}else {
			if("/xingkong/user/tologin".equals(map.get(url)) || "/xingkong/user/index".equals(map.get(url)) 
					|| "/xingkong/user/login".equals(map.get(url)) 
					|| "/xingkong/order/countTotal".equals(map.get(url))
					|| "/xingkong/user/toreg".equals(map.get(url))
					|| "/xingkong/user/toforget".equals(map.get(url))
					|| "/xingkong/user/reg".equals(map.get(url))
					|| "/xingkong/user/admin".equals(map.get(url))){
				arg0.invoke();
			}else {
				if(this.isAjax(c)){
					c.renderJson(new ResponseContent(StaticFields.WRONG, "请求不正常", null));
					return;
				}
				c.redirect("/user/index");
			}
		}
	}
	/**
	 * 判断是否是ajax请求
	 * @param c
	 * @return true 是false 不是
	 */
	public boolean isAjax(Controller c){
		return "XMLHttpRequest".equals(c.getHeader("x-requested-with"));
	}

}
